package com.wanmait.schedule.controller;

import com.wanmait.schedule.entity.Role;
import com.wanmait.schedule.entity.Teacher;
import com.wanmait.schedule.service.RoleService;
import com.wanmait.schedule.shiro.ShiroRealm;
import com.wanmait.schedule.util.AjaxResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 角色表 前端控制器
 * </p>
 *
 * @author wanmait
 * @since 2022-12-05
 */
@RestController
@RequestMapping("/manage/role")
@RequiresPermissions("manage:role_permission")
public class RoleController {

    @Resource
    private RoleService roleService;

    //角色列表查询
    @GetMapping("list")
    public AjaxResult list(){
        return AjaxResult.success(roleService.list());
    }

    //新增角色 修改角色
    @PostMapping("save")
    public AjaxResult save(@RequestBody Role role){
        //Teacher teacher = (Teacher) request.getAttribute("teacher");
        if(role.getId()==null){
            List<Role> roles = roleService.list();
            for (Role i : roles) {
                if(i.getRoleName().equals(role.getRoleName())){
                    return AjaxResult.error(10001,"角色名已存在");
                }
            }
            roleService.save(role);
        }
        else{
            roleService.updateById(role);
        }
        return AjaxResult.success("保存成功",role);
    }

    //删除角色
    @GetMapping("delete")
    public AjaxResult delete(Integer id){
        roleService.removeById(id);

        DefaultWebSecurityManager securityManager = (DefaultWebSecurityManager) SecurityUtils.getSecurityManager();
        ShiroRealm shiroRealm = (ShiroRealm) securityManager.getRealms().iterator().next();
        shiroRealm.getAuthorizationCache().clear();

        return AjaxResult.success("删除成功");
    }
}
